package edu.ynu.se.xiecheng.achitectureclass.controller;

import edu.ynu.se.xiecheng.achitectureclass.entity.CameraData;
import edu.ynu.se.xiecheng.achitectureclass.service.ICameraService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/camera")
public class CameraController {

    @Autowired
    private ICameraService cameraService;

    @PostMapping("/capture/{deviceId}")
    public ResponseEntity<?> captureImage(
            @PathVariable Long deviceId,
            @RequestHeader("Authorization") String token) {
        // 验证token
        if (!token.equals("Bearer " + "ra.5re72ai38g4y7gky9ghls5dzb2equqku-491d6ysuja-0bzlevz-5zrd54nns")) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        CameraData cameraData = cameraService.captureAndSave(deviceId);
        if (cameraData != null) {
            return ResponseEntity.ok().body("Image captured successfully");
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to capture image");
    }

    @GetMapping("/latest/{deviceId}")
    public ResponseEntity<byte[]> getLatestImage(@PathVariable Long deviceId) {
        CameraData cameraData = cameraService.getLatestImage(deviceId);
        if (cameraData != null && cameraData.getPhoto() != null) {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.IMAGE_JPEG);
            return new ResponseEntity<>(cameraData.getPhoto(), headers, HttpStatus.OK);
        }
        return ResponseEntity.notFound().build();
    }
} 